//
//  RMMMineViewController.m
//  Romomo
//
//  Created by puman on 16/9/30.
//  Copyright © 2016年 mazegong. All rights reserved.
//

#import "RMMMineViewController.h"
#import "RMMMineHeadView.h"
#import "RMMMineHeadTableViewCell.h"
#import "RMMLongingViewController.h"
#import "RMMLandingedHeadView.h"
#import "RMMSetViewController.h"
#import "RMMMineWalletTableViewCell.h"
#import "RMMMineAdressTableViewCell.h"
#import "RMMMineMyWalletViewController.h"
#import "RMMOderAdressViewController.h"
#import "RMMPersonBandDingViewController.h"
#import "RMMMyHuLiViewController.h"

@interface RMMMineViewController ()<UITableViewDelegate, UITableViewDataSource>

@end

@implementation RMMMineViewController
{
    RMMMineHeadView *_mineHeadView;
    RMMLandingedHeadView *_landingView;
    UITableView *_tableView;
    RMMNotNetWorkView *_networkView;
    UIScrollView *_scrollView;
    NSDictionary *_dic;
    BOOL _isFirstComeIn;
    CGFloat _huLiLiaoChengHeight;
    CGFloat _adressHeight;
    NSString *_adreeType;
    NSString *_huLiType;
    NSString *_walletType;
    NSArray *_bomArray;
    NSString *_balance;
    NSString *_cardCount;
    BOOL _goToBuyServices;
}
- (void)dealloc{
    NS_REM(@"LANDSUCESS", nil);
    NS_REM(@"BIANJIDIZHI", nil);
    NS_REM(@"TUICHUDENGLU", nil);
    NS_REM(@"UPDATEMINEDATA", nil);
    NS_REM(@"GOTOBUYSERVICES", nil);
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (_goToBuyServices) {
        UITabBarController *VC = (UITabBarController *)keyWidow.rootViewController;
        [VC setSelectedIndex:0];
    }
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    if (_isFirstComeIn) {
        _isFirstComeIn = NO;
        if ([RMMFileManager shareHandle].isLoginSuccess) {
            [self qqLonin];
        }
    }
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    _goToBuyServices = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self addViews];
    NS_ADD(upDateMineData, @"UPDATEMINEDATA", nil);
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBar.translucent = NO;
    self.view.backgroundColor = kWhiteColor;
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        if ([RMMFileManager shareHandle].isLoginSuccess) {
            [self getCuatBomeWithCust_id:[RMMFileManager shareHandle].userDic[@"CUST_ID"]];
        } else {
            [_tableView.mj_header endRefreshing];
        }
     }];

    // Do any additional setup after loading the view.
}
- (void)tuiChuDengLu{
    _balance = @"0.00";
    _cardCount = @"0";
    [_tableView reloadData];

}
- (void)upDateMineData{
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"org_no"] = Org_no;
    parDic[@"cust_id"] = [[RMMFileManager shareHandle].userDic objectForKey:@"CUST_ID"];
    NSString *url = UserInfo;
    [OSRequestManager requestWithUrlString:url parDic:parDic method:GET finish:^(NSDictionary *dataDic) {
        NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
        if ([status isEqualToString:@"1"]) {
            [RMMFileManager shareHandle].userDic = [RMMFileManager setValueForDic:dataDic[@"data"]];
            [self qqLonin];
            [self getCuatBomeWithCust_id:[[RMMFileManager shareHandle].userDic objectForKey:@"CUST_ID"]];
        }
        [_tableView reloadData];
    } error:^(NSError *errors) {
        
    } view:self.view];
}
- (void)addViews{
    _isFirstComeIn = YES;
    _huLiLiaoChengHeight = 110;
    _adressHeight = 110;
    _huLiType = @"0";
    _walletType = @"0";
    _adreeType = @"0";
    _balance = @"0.00";
    _cardCount = @"0";
    NS_ADD(tuiChuDengLu, @"TUICHUDENGLU", nil);
    self.navigationController.navigationBar.backgroundColor = kWhiteColor;
    _mineHeadView = [[RMMMineHeadView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 200)];
    BUTTON_S(_mineHeadView.logingBut, logingNow);
    [self.view addSubview:_mineHeadView];
    
    _landingView = [[RMMLandingedHeadView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 150)];
    _landingView.hidden = YES;
    BUTTON_S(_landingView.setBut, setButClcik);
    [self.view addSubview:_landingView];

    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth - 30, 145)];

    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, _mineHeadView.bottom, kScreenWideth, kScreenHeight - _mineHeadView.bottom - 49) style:(UITableViewStylePlain)];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.separatorStyle = NO;
    [_tableView registerClass:[RMMMineHeadTableViewCell class] forCellReuseIdentifier:@"Cell"];
    [_tableView registerClass:[RMMMineAdressTableViewCell class] forCellReuseIdentifier:@"AdressCell"];
    [_tableView registerClass:[RMMMineWalletTableViewCell class] forCellReuseIdentifier:@"WalletCell"];
    [self.view addSubview:_tableView];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 60)];
    view.backgroundColor = kWhiteColor;
    _tableView.tableFooterView = view;
    UIButton *bottomBut = [UIButton buttonWithType:(UIButtonTypeCustom)];
    bottomBut.frame = CGRectMake(kScreenWideth / 2 - 128, kRow , 256, 40);
    bottomBut.backgroundColor = kWhiteColor;
    bottomBut.layer.borderColor= kBasicColor.CGColor;
    bottomBut.layer.borderWidth = 1;
    [bottomBut setTitleColor:kBasicColor forState:(UIControlStateNormal)];
    bottomBut.titleLabel.font = kBFont(14);
    bottomBut.layer.masksToBounds = YES;
    bottomBut.layer.cornerRadius = 20;
    BUTTON_S(bottomBut, callKeFuMoblie);
    [bottomBut setTitle:@"工作日客服: 137-1767-7487" forState:(UIControlStateNormal)];
    [view addSubview:bottomBut];
    NS_ADD(qqLonin, @"LANDSUCESS", nil);
    NS_ADD(editorAdress, @"BIANJIDIZHI", nil);
    NS_ADD(goToBuyServices , @"GOTOBUYSERVICES", nil);
    _goToBuyServices = NO;
    
    _networkView = [[RMMNotNetWorkView alloc] initWithFrame:CGRectMake(0, _mineHeadView.bottom, kScreenWideth, kScreenHeight - _mineHeadView.bottom - 49)];
    _networkView.hidden = YES;
    BUTTON_S(_networkView.button, networkBut);
    [self.view addSubview:_networkView];
}
- (void)goToBuyServices{
    _goToBuyServices = YES;
}
- (void)editorAdress{
    [self networkBut];
}
- (void)networkBut{
    NSString *cust_id = [RMMFileManager retrunObjWith:[RMMFileManager shareHandle].userDic[@"CUST_ID"]];
    [self getCuatBomeWithCust_id:cust_id];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 3;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 1) {
        return 120;
    } else if (indexPath.row == 0) {
        return _huLiLiaoChengHeight;
    } else {
        return _adressHeight;
    }
}
//- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
//    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 60)];
//    view.backgroundColor = kWhiteColor;
//    
//    UIButton *bottomBut = [UIButton buttonWithType:(UIButtonTypeCustom)];
//    bottomBut.frame = CGRectMake(kScreenWideth / 2 - 128, kRow, 256, 40);
//    bottomBut.backgroundColor = kWhiteColor;
//    bottomBut.layer.borderColor= kBasicColor.CGColor;
//    bottomBut.layer.borderWidth = 1;
//    [bottomBut setTitleColor:kBasicColor forState:(UIControlStateNormal)];
//    bottomBut.titleLabel.font = kBFont(14);
//    bottomBut.layer.masksToBounds = YES;
//    bottomBut.layer.cornerRadius = 20;
//    [bottomBut setTitle:@"联系客服: 400-002-6565" forState:(UIControlStateNormal)];
//    BUTTON_S(bottomBut, callKeFu);
//    [view addSubview:bottomBut];
//
//    return view;
//}
//- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
//    return kHalf + kRow;
//}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        RMMMineHeadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.type = _huLiType;
        cell.tag = 99;
        return cell;
    } else if (indexPath.row == 1) {
        RMMMineWalletTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WalletCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.type = _walletType;
        cell.balance = _balance;
        cell.cardCount = _cardCount;
        return cell;
    } else {
        RMMMineAdressTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AdressCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (_dic != nil) {
            cell.dic = _dic;
        }
        cell.type = _adreeType;
        return cell;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([RMMFileManager shareHandle].isLoginSuccess) {
        NSString *cust_id = [RMMFileManager retrunObjWith:[RMMFileManager shareHandle].userDic[@"CUST_ID"]];
        if(cust_id.length){
            if (indexPath.row == 0) {
                RMMMyHuLiViewController *VC = [[RMMMyHuLiViewController alloc] init];
                [self.navigationController pushViewController:VC animated:YES];
            } else if (indexPath.row == 1) {
                RMMMineMyWalletViewController *VC = [[RMMMineMyWalletViewController alloc] init];
                [self.navigationController pushViewController:VC animated:YES];
            } else {
                RMMOderAdressViewController *VC = [[RMMOderAdressViewController alloc] init];
                VC.titleName = @"我的地址";
                VC.isHome = [RMMFileManager shareHandle].fuWuType;
                [self.navigationController pushViewController:VC animated:YES];
            }

        } else {
            [self addLoginAlertView];
        }
    }
}
- (void)qqLonin{
    _landingView.hidden = NO;
    _mineHeadView.hidden = YES;
    _tableView.frame = CGRectMake(0, _landingView.bottom, kScreenWideth, kScreenHeight - 64 - _landingView.bottom);
    _landingView.dic = [RMMFileManager shareHandle].userDic;
    NSString *cust_id = [RMMFileManager retrunObjWith:[RMMFileManager shareHandle].userDic[@"CUST_ID"]];
    if (![RMMFileManager shareHandle].fuWuType.length) {
        [RMMFileManager shareHandle].fuWuType = @"1";
    }
    [self getCuatBomeWithCust_id:cust_id];
}
// 设置
- (void)setButClcik{
    RMMSetViewController *VC = [[RMMSetViewController alloc] init];
    VC.exitLanding = ^void(){
        _landingView.hidden = YES;
        _mineHeadView.hidden = NO;
        _adreeType = @"0";
        _adressHeight = 110.0;
        _huLiType = @"0";
        _huLiLiaoChengHeight = 110;
        [RMMFileManager shareHandle].userDic = nil;
        [RMMFileManager shareHandle].isLoginSuccess = NO;

        _tableView.frame = CGRectMake(0, _mineHeadView.bottom, kScreenWideth, kScreenHeight - _mineHeadView.bottom - 49);
        [_tableView reloadData];

    };
    [self.navigationController pushViewController:VC animated:YES];
}
// 马上登陆
- (void)logingNow{
    RMMLongingViewController *loginVC = [[RMMLongingViewController alloc] init];
    [self.navigationController pushViewController:loginVC animated:YES];
}
// 联系客服
- (void)callKeFu{
    [RMMFileManager  callKeFuWithPhoneNumber:NumberSJ onView:self.view];
}
- (void)callKeFuMoblie{
    [RMMFileManager  callKeFuWithPhoneNumber:@"13717677487" onView:self.view];
}
// 获取套餐详情
- (void)getCuatBomeWithCust_id:(NSString *)cust_id{
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"org_no"] = Org_no;
    parDic[@"cust_id"] = cust_id;
    NSString *url = GetCarDetailsUrl;
    [OSRequestManager requestWithUrlString:url parDic:parDic network:^(BOOL isNetwork) {
        if (isNetwork) {
            _networkView.hidden = YES;
        } else {
            _networkView.hidden = NO;
        }
    } method:GET finish:^(NSDictionary *dataDic) {
        NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
        if ([status isEqualToString:@"1"]) {
            _landingView.yanZhiValue = [NSString stringWithFormat:@"%@",dataDic[@"data"][@"AVA_POINTS"]];
            _landingView.lvValue = [NSString stringWithFormat:@"%@",dataDic[@"data"][@"LVL_NAME"]];
            NSDictionary *dics = [RMMFileManager setValueForDic:dataDic[@"data"]];
            _balance = [NSString stringWithFormat:@"%.2f",[dics[@"CardBalance"] floatValue]];
            _cardCount = [NSString stringWithFormat:@"%@",dics[@"VoucherCount"]];
            _bomArray = dics[@"Cust_Bom"];
            if (!_bomArray.count) {
                _huLiType = @"1";
                _huLiLiaoChengHeight = 110;
            } else {
                _huLiLiaoChengHeight = 210;
                _huLiType = @"2";
                RMMMineHeadTableViewCell *cell = [self.view viewWithTag:99];
                [_scrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
                [cell.scrollBackView addSubview:_scrollView];
                for (int i = 0; i < _bomArray.count; i++) {
                    NSDictionary *dic = [RMMFileManager setValueForDic:_bomArray[i]];
                    UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(10 + 110 * i, 10, 90, 90)];
                    imageV.layer.cornerRadius = 3;
                    imageV.layer.masksToBounds = YES;
                    imageV.userInteractionEnabled = YES;
                    [imageV sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kBaseImageUrl,dic[@"IMAGEURL"]]] placeholderImage:[UIImage imageNamed:@"加载中@3x"]];
                    [_scrollView addSubview:imageV];
                    
                    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(imageV.left, imageV.bottom, imageV.width, 45)];
                    label.textAlignment = NSTextAlignmentCenter;
                    label.font = kFont(12);
                    label.textColor = COLORFROMCODE(0x2C2C2C, 1);
                    label.text = [RMMFileManager retrunObjWith:dic[@"BOM_NAME"]];
                    [_scrollView addSubview:label];
                }
                [_scrollView setContentSize:CGSizeMake(20 + _bomArray.count * 90 + (_bomArray.count - 1) * 20, 145)];
            }
            if ([dataDic[@"data"][@"Addres"] isKindOfClass:[NSNull class]]) {
                _adressHeight = 110.0;
                _adreeType = @"2";
            } else {
                _dic = [RMMFileManager setValueForDic:dics[@"Addres"]];
                _adressHeight = 130.0;
                _adreeType = @"1";
            }
        } else {
            [RMMFileManager MBProgressWith:dataDic[@"message"] onView:self.view];
        }
        [_tableView reloadData];
        [_tableView.mj_header endRefreshing];
    } error:^(NSError *errors) {
        [_tableView.mj_header endRefreshing];
    } view:self.view];
}
- (void)addLoginAlertView{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"需要先前往绑定您的手机号,才能给你提供更好的服务" preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *actionA = [UIAlertAction actionWithTitle:@"前往" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        RMMPersonBandDingViewController *loginVC = [[RMMPersonBandDingViewController alloc] init];
        loginVC.titleName = @"绑定手机号";
        loginVC.blocks = ^void(NSString *string,NSString *cust_id){
        };
        [self.navigationController pushViewController:loginVC animated:YES];
        
    }];
    UIAlertAction *actionB = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertController addAction:actionA];
    [alertController addAction:actionB];
    [self presentViewController:alertController animated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
